package com.lw.leetcode.linked.b;

import com.lw.leetcode.linked.ListNode;

import java.util.Stack;

/**
 * Created with IntelliJ IDEA.
 * stack
 * 2487. 从链表中移除节点
 *
 * @author liw
 * @version 1.0
 * @date 2022/11/28 20:38
 */
public class RemoveNodes {

    public ListNode removeNodes(ListNode head) {
        ListNode root = new ListNode(Integer.MAX_VALUE);
        root.next = head;
        Stack<ListNode> stack = new Stack<>();
        stack.add(root);
        while (head != null) {
            ListNode peek = stack.peek();
            while (peek.val < head.val) {
                stack.pop();
                peek = stack.peek();
            }
            peek.next = head;
            stack.add(head);
            head = head.next;
        }
        return root.next;
    }

}
